<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * CFD API接口（微信）
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Phil Sturgeon, Chris Kacerguis
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class Ticket extends REST_Controller {
	private $productConfig;
	private $user_info;

	public function __construct(){  
        parent::__construct();
        $this->load->config('cfd');
        //加载通行证类
        $this->load->library('passPort');
        $this->passportClass = $this->passport;
        
        $this->passportClass->setPlatform($this->config->item('platform'));//设置平台
		$this->user_info = $this->passportClass->checkCookieAuthCode('','',true);
		if(empty($this->user_info)){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 200001,
                $this->config->item('rest_message_field_name') => '请先登陆'
            ), REST_Controller::HTTP_OK);
		}
    }

    /**
     * 购买抵扣券
     */
    public function buy_post(){
    	$post = $this->post();
        if(empty($post)) {
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
        }
		
		$num	=	$post['num'];
		if ($num <=0 || !is_numeric($num) || strpos($num,".")!==false ){
			 $this->response(array(
                $this->config->item('rest_status_field_name') => 100002,
                $this->config->item('rest_message_field_name') => '购买数量错误'
            ), REST_Controller::HTTP_OK);
		}
		
		$uid	=	$this->user_info['uid'];
		$data	=	array(
			'uid'	=>	$uid,
			'num'	=>	$num,	
		);
		
		$sdate	=	date("Y-m-d 00:00:00");
		$edate	=	date("Y-m-d 23:59:59");
		$this->load->library('TicketClass');
		$buyNum	=	$this->ticketclass->getBuyTicketNum($uid,$sdate,$edate);
		if(bcadd($buyNum,$num)>10){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100002,
                $this->config->item('rest_message_field_name') => '体验券每天最多购买10张，你今天已购买'.$buyNum."张",
            ), REST_Controller::HTTP_OK);
		}

		$rs = $this->ticketclass->buy($data);
		if($rs['errno']==0){
			$this->response(array(
				$this->config->item('rest_status_field_name')=>0
			), REST_Controller::HTTP_OK);
		}else{
			$this->response(array(
                $this->config->item('rest_status_field_name') => $rs['errno'],
                $this->config->item('rest_message_field_name') => $rs['msg']
            ), REST_Controller::HTTP_OK);
		}
    }
}
